package com.hjm.common.core.domain;
import com.hjm.common.core.enums.ResultCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;


@Getter
@Setter
@ToString
public class Result<T> {
    int code;    //  状态码
    String msg;  // 失败原因
    T data;      // 响应的数据

    public static <T> Result<T> ok() {
        return assembleResult(null, ResultCode.SUCCESS);
    }

    public static <T> Result<T> ok(T data) {
        return assembleResult(data, ResultCode.SUCCESS);
    }

//    public static <T> Result<T> ok(String msg) {
//        return assembleResult(null, ResultCode.SUCCESS.getCode(), msg);
//    }

    public static <T> Result<T> ok(String msg, T data) {
        return assembleResult(data, ResultCode.SUCCESS.getCode(), msg);
    }


    /**
     * 指定错误码
     *
     * @param resultCode 指定错误码
     * @param <T>
     * @return
     */
    public static <T> Result<T> fail(ResultCode resultCode) {
        return assembleResult(null, resultCode);
    }

    public static <T> Result<T> fail() {
        return assembleResult(null, ResultCode.FAILED);
    }

    public static <T> Result<T> fail(int code, String msg) {
        return assembleResult(null, code, msg);
    }

    public static <T> Result<T> fail(String msg) {
        return assembleResult(null, ResultCode.FAILED.getCode(), msg);
    }

    //****
    public static <T> Result<T> fail(String msg, ResultCode resultCode) {
        return assembleResult(null, resultCode.getCode(), msg);
    }

    public static <T> Result<T> fail(T data) {
        return assembleResult(data, ResultCode.FAILED);
    }

    public static <T> Result<T> fail(String msg, T data) {
        return assembleResult(data, ResultCode.FAILED.getCode(), msg);
    }

    //提取出来公共的方法：根据传入 参数的不同 但是 做出的行为是相同的
    private static <T> Result<T> assembleResult(T data, ResultCode resultCode) {
        Result<T> r = new Result<>();
        r.setCode(resultCode.getCode());
        r.setData(data);
        r.setMsg(resultCode.getMsg());
        return r;
    }


    private static <T> Result<T> assembleResult(T data, int code, String msg) {
        Result<T> r = new Result<>();
        r.setCode(code);
        r.setData(data);
        r.setMsg(msg);
        return r;
    }

    public static <T> Boolean isError(Result<T> ret) {
        return !isSuccess(ret);
    }

    public static <T> Boolean isSuccess(Result<T> ret) {
        return ResultCode.SUCCESS.getCode() == ret.getCode();
    }

}
